package 剑指专题.二叉树;


/*
 * Author：江松
 * Date：2023/3/24 11:26
 *
 二叉搜索树的第k个节点:
 L，mid，R有序——中序遍历，计数问题cnt应该做全局变量
 */

public class Main3 {

    public class TreeNode {
        int val = 0;
        TreeNode left = null;
        TreeNode right = null;
        public TreeNode(int val) {
            this.val = val;
        }
    }

    int k,cnt;
    int ans=-1;
    public void dfs(TreeNode root){
        if(root==null)return;
        dfs(root.left);
        cnt++;
        System.out.println("val:"+root.val+" ,cnt"+cnt);
        if(cnt==k){
            ans=root.val;
            return;
        }
        dfs(root.right);
    }

    public int KthNode (TreeNode root, int k) {
        if(root==null||k<=0)return -1;
        this.k=k;
        dfs(root);
        return ans;
    }

}
